#include "backtest/csv_data_loader.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>

std::vector<MarketData> CsvDataLoader::load_data(const std::string& symbol,
                                               const std::string& start_time,
                                               const std::string& end_time) {
    std::vector<MarketData> result;
    
    try {
        std::ifstream file(data_path_);
        if (!file.is_open()) {
            std::cerr << "Failed to open file: " << data_path_ << std::endl;
            return result;
        }
        
        std::string line;
        // 读取并跳过标题行
        std::getline(file, line);
        
        // 读取数据行
        while (std::getline(file, line)) {
            std::stringstream ss(line);
            std::string timestamp, sym, open_str, high_str, low_str, close_str, volume_str;
            
            // 解析CSV行
            std::getline(ss, timestamp, ',');
            std::getline(ss, sym, ',');
            std::getline(ss, open_str, ',');
            std::getline(ss, high_str, ',');
            std::getline(ss, low_str, ',');
            std::getline(ss, close_str, ',');
            std::getline(ss, volume_str, ',');
            
            // 检查是否是我们要找的交易对
            if (sym != symbol) {
                continue;
            }
            
            // 检查时间戳是否在指定范围内
            if (!is_timestamp_in_range(timestamp, start_time, end_time)) {
                continue;
            }
            
            // 创建市场数据对象
            MarketData data;
            data.timestamp = timestamp;
            data.symbol = sym;
            
            try {
                data.open = std::stod(open_str);
                data.high = std::stod(high_str);
                data.low = std::stod(low_str);
                data.close = std::stod(close_str);
                data.volume = std::stod(volume_str);
            } catch (const std::exception& e) {
                std::cerr << "Error parsing numeric values: " << e.what() << std::endl;
                continue;
            }
            
            result.push_back(data);
        }
        
        // 按时间戳排序
        std::sort(result.begin(), result.end(), [](const MarketData& a, const MarketData& b) {
            return a.timestamp < b.timestamp;
        });
        
    } catch (const std::exception& e) {
        std::cerr << "Error loading data: " << e.what() << std::endl;
    }
    
    return result;
}

bool CsvDataLoader::is_timestamp_in_range(const std::string& timestamp,
                                        const std::string& start_time,
                                        const std::string& end_time) {
    // 简单的字符串比较，假设时间戳格式为 YYYY-MM-DD HH:MM:SS
    return timestamp >= start_time && timestamp <= end_time;
}